using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.Reflection;
using System;
using UnityEngine.Events;

public class EventSelectWindow : EditorWindow
{
    public UnityEventBase @event;
    public string str;
    Vector2 scrollPos;

    Type targetFunction;
    bool functionSelectFold;
    string functionSelectLayout;
    MethodInfo targetMethod; 
    List<Type> functions = new List<Type>();
    List<MethodInfo> methods = new List<MethodInfo>();

    public static void ShowWindow(UnityEventBase @event){
        EventSelectWindow window = CreateInstance(typeof(EventSelectWindow)) as EventSelectWindow;
        window.@event = @event;
        window.ShowUtility();
    }

    private void OnEnable() {
        targetFunction = null;
        functionSelectLayout = "请选择方法类型";
        Assembly assembly = Assembly.GetAssembly(typeof(GameManager));
        Type[] types = assembly.GetTypes();
        foreach(Type t in types){
            if(t.FullName.Contains("Func"))
                functions.Add(t);
        }
    }

    void OnGUI()
    {
        functionSelectFold = EditorGUILayout.BeginFoldoutHeaderGroup(functionSelectFold, functionSelectLayout);
        if(functionSelectFold){
            foreach(Type type in functions){
                if(GUILayout.Button(type.FullName)){
                    functionSelectFold = false;
                    targetFunction = type;
                    functionSelectLayout = type.FullName;
                    SetMethod();
                }
            }
        }
        if(targetFunction != null){
            EditorGUILayout.LabelField("选择一个方法：");
            scrollPos = EditorGUILayout.BeginScrollView(scrollPos);
            foreach(MethodInfo mtd in methods){
                if(GUILayout.Button(mtd.Name)){
                    targetMethod = mtd;
                }
            }
            EditorGUILayout.EndScrollView();
        }
        if(targetMethod != null){

            EditorGUILayout.LabelField("当前选择：",targetMethod.Name);

            if(GUILayout.Button("提交")){
                if(@event != null){
                    IFunctionEvent e = (IFunctionEvent)@event;
                    e.Add(targetMethod);
                    Close();
                }
            }
        }
    }
    void SetMethod(){
        if(targetFunction != null){
            methods = new List<MethodInfo>(
                targetFunction.GetMethods(BindingFlags.Public | BindingFlags.Static)
            );
        }
    }
    void OnInspectorUpdate(){
        Repaint();
    }
}
